package com.yznote.cloudesk.user.server.impl;

import com.yznote.cloudesk.common.exception.YException;
import com.yznote.cloudesk.common.pojo.Bar;
import com.yznote.cloudesk.user.mapper.BarMapper;
import com.yznote.cloudesk.user.server.BarServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BarServerImpl implements BarServer {
    @Autowired
    BarMapper barMapper;

    @Override
    public List<Bar> getBarList(Long userId) {
        return barMapper.getBarList(userId);
    }

    @Override
    public void insertBar(Long userId, Long fileId) {
        int maxIndex = barMapper.getMaxBar(userId);
        barMapper.insetBar(userId,fileId,maxIndex+1, LocalDateTime.now());
    }

    @Override
    public void removeBar(Long userId, Integer index) {
        stopMove(index);
        barMapper.removeBar(userId,index);
    }

    @Override
    @Transactional
    public void swapBar(Long userId, Integer index1, Integer index2) {
        stopMove(index1,index2);
        LocalDateTime now = LocalDateTime.now();
        barMapper.updataBar(userId,index1,-1,now);
        barMapper.updataBar(userId,index2,index1,now);
        barMapper.updataBar(userId,-1,index2,now);
    }

    public void stopMove(Integer... indexs){
        for (int index:indexs){
            if (index==0){
                throw new YException("不能改变位置为0的bar",500,null);
            }
        }
    }
}
